<template>
  <div :style="inlineStyle">
    <div v-if="field.componentName === 'group'">
      <el-card shadow="never" style="margin-top: 20px; margin-bottom: 20px">
        <div slot="header" style="padding-bottom: 20px">{{ field.label }}</div>

        <template v-if="field.inline">
          <template v-for="(subField, subIndex) in field.fields" :key="subIndex">
            <FieldComponent
              :field="subField"
              :formData="formData[field.valueName]"
              :path="getFieldPath(field.valueName, path)"
            />
          </template>
        </template>

        <template v-else>
          <el-row :gutter="20">
            <template v-for="(subField, subIndex) in field.fields" :key="subIndex">
              <el-col :span="subField.span">
                <FieldComponent
                  :field="subField"
                  :formData="formData[field.valueName]"
                  :path="getFieldPath(field.valueName, path)"
                />
              </el-col>
            </template>
          </el-row>
        </template>
      </el-card>
    </div>

    <el-form-item
      v-else
      :label="field.label"
      :prop="getFieldProp(field.valueName, path)"
      :label-position="field['label-position']"
      :label-width="field['label-width']"
    >
      <component
        v-if="!excludedComponents.includes(field.componentName)"
        :is="field.componentName"
        v-bind="field.props"
        v-model="formData[field.valueName]"
      >
        <template v-if="field.componentName === 'el-radio-group'">
          <el-radio v-for="option in field.options" :value="option.value">
            {{ option.label }}
          </el-radio>
        </template>

        <template v-if="field.componentName === 'el-select'">
          <el-option
            v-for="option in field.options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          ></el-option>
        </template>
      </component>

      <div v-if="field.componentName === 'el-cascader-panel'">
        <el-cascader-panel v-model="formData[field.valueName]" :options="field.options" />
      </div>

      <!-- 表格组件 -->
      <div v-if="field.componentName === 'el-table'" style="width: 100%">
        <el-button type="primary" @click="showAddTableRow(field.valueName)" style="margin-bottom: 10px">
          添加
        </el-button>

        <el-table :data="formData[field.valueName]" style="width: 100%" border>
          <el-table-column
            v-for="(column, colIndex) in field.columns"
            :key="colIndex"
            :prop="column.prop"
            :label="column.label"
            :width="column.width || 'auto'"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              {{ getProp(scope.row, column.prop) }}
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作">
            <template #default="scope">
              <el-button link type="primary" size="small" @click.prevent="editRow(scope.$index)"> 修改 </el-button>
              <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.$index)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form-item>

    <el-dialog v-if="field.componentName === 'el-table'" v-model="dialogFormVisible" :title="field.title">
      <el-form ref="tableFormRef" :model="tableFormData" :rules="field.rules">
        <template v-for="subField in field.fields">
          <FieldComponent :field="subField" :formData="tableFormData" />
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addTableRow">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-if="field.componentName === 'el-table'" v-model="editDialogFormVisible" :title="field.title">
      <template v-for="subField in field.fields">
        <FieldComponent :field="subField" :formData="editTableFormData" />
      </template>
      <template #footer>
        <el-button @click="editDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateTableRow">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { calculateFunction, initFormData } from './js/FieldComponent.js';
import { ElMessage } from 'element-plus';

const { field, formData, path } = defineProps({
  field: Object,
  formData: Object,
  path: String
});

const excludedComponents = ['el-table', 'el-cascader-panel'];

const inlineStyle = field.inline ? { display: 'inline-block', marginRight: '20px' } : {};

/** 表格操作 */
const dialogFormVisible = ref(false);
const editDialogFormVisible = ref(false);
const tableFormData = ref({});
const editTableFormData = ref({});
const currentRowIndex = ref(null);
const tableFormRef = ref({});

function showAddTableRow() {
  dialogFormVisible.value = true;
  tableFormData.value = initFormData(field);
}

if (field.componentName === 'el-table') {
  watch(
    () => tableFormData,
    (newVal, oldVal) => {
      calculateFunction(field, tableFormData.value);
      // 在这里处理变化后的逻辑
    },
    { deep: true }
  ); // 深度监听以捕捉对象内部值的变化
}

function addTableRow() {
  tableFormRef.value.validate((valid, error) => {
    if (valid) {
      // 表单验证通过，执行添加操作
      formData[field.valueName].push(tableFormData.value.data);
      dialogFormVisible.value = false;
    } else {
      ElMessage.error('表单验证失败！');
      for (const field in error) {
        ElMessage.error(error[field][0].message);
      }
    }
  });
}

function deleteRow(index) {
  formData[field.valueName].splice(index, 1);
}

function editRow(index) {
  editDialogFormVisible.value = true;
  currentRowIndex.value = index;
  editTableFormData.value = { data: { ...formData[field.valueName][index] } };
  watch(
    () => editTableFormData,
    (newVal, oldVal) => {
      calculateFunction(field, editTableFormData.value);
      // 在这里处理变化后的逻辑
    },
    { deep: true }
  ); // 深度监听以捕捉对象内部值的变化
}

function updateTableRow() {
  formData[field.valueName][currentRowIndex.value] = editTableFormData.value.data;
  editDialogFormVisible.value = false;
}

function getProp(row, prop) {
  let matches;

  function search(row) {
    if (typeof row !== 'object' || row === null) return;

    for (let key in row) {
      if (row.hasOwnProperty(key)) {
        if (key === prop) {
          matches = row[key];
        }

        if (typeof row[key] === 'object') {
          search(row[key]);
        }
      }
    }
  }

  search(row);

  if (Array.isArray(matches)) {
    return matches.join(',');
  } else if (typeof matches === 'string' && matches.includes('http')) {
    // 拆分多个 URL
    const urls = matches.split(',').map((url) => url.trim());
    const fileNames = urls.map((url) => {
      try {
        const parsedUrl = new URL(url);
        return decodeURIComponent(parsedUrl.pathname.split('/').pop());
      } catch (error) {
        // 如果解析失败，返回原始 URL
        return url;
      }
    });
    matches = fileNames.join(', ');
  }

  return matches;
}

/** 获取字段的prop */
function getFieldProp(valueName, currentPath) {
  if (currentPath) {
    return `${currentPath}.${valueName}`;
  }
  return valueName;
}

function getFieldPath(valueName, currentPath) {
  if (currentPath) {
    return `${currentPath}.${valueName}`;
  }
  return valueName;
}
</script>

<style scoped lang="scss"></style>
